// pages/posts/post.js
var util = require('../../utils/util.js'); 
var app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    hidden: false,
    listInfo: {},
    bannerList: {},
    picker1Value: 0,
    picker1Range: ['国三', '国四', '国五'],
    timeValue: '08:08',
    dateValue: '2018-10-13',
    dateValues: '2018-10-13',
    region: ['广东省', '广州市', '海珠区'],
    customItem: '全部',
    checolors: 0,
    checolor: ['黑', '白', '红', '蓝', '灰', '银白', '银灰', '粉红', '天蓝', '香槟'],
    baoxiansj: 0,
    baoxian: ['无', '2018', '2019', '2020', '2021', '2022', '2023', '2024', '2025', '2026', '2027', '2028', '2029', '2030', '2031', '2032', '2033', '2034', '2035', '2036', '2037', '2038', '2039', '2040', '2041', '2042', '2043', '2044', '2045', '2046', '2047', '2048', '2049', '2050', '2051', '2052', '2053', '2054', '2055', '2056', '2057', '2058'],
    info:{},
    productInfo: {
      bannerInfo: [],
      weixinInfo: []
    },
    bannerInfoUrl: [],
    weixinInfoUrl: [],
    is_license:''
  },
  

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.showLoading({
      title: '加载中',
    })
    //获取详情
    this.getDetail(options.id);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分--享
   */
  onShareAppMessage: function () {
    console.log('share');
  },

  normalPickerBindchange: function (e) {
    this.setData({
      picker1Value: e.detail.value
    })
  },
  timePickerBindchange: function (e) {
    this.setData({
      timeValue: e.detail.value
    })
  },
  datePickerBindchange: function (e) {
    console.log(e);
    this.setData({
      dateValue: e.detail.value
    })
  },
  datePickerBindchanges: function (e) {
    console.log(e);
    this.setData({
      dateValues: e.detail.value
    })
  },
  // 地址
  bindRegionChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      region: e.detail.value
    })
  },

  baoxians: function (e) {
    this.setData({
      baoxiansj: e.detail.value
    })
  },
  colorss: function (e) {
    this.setData({
      checolors: e.detail.value
    })
  },

  //获取详情
  getDetail:function(id){
    var that = this;
    wx.request({
      url: app.d.hostUrl + 'api/car/get_car',
      data: {
        id: id
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'mchnt': getApp().d.mchnt 
      },
      success: function (res) {
        console.log(res);
        var productInfo = that.data.productInfo;

        var bannerArr = res.data.data.images.split('|');
        for (var i = 0, h = bannerArr.length; i < h; i++) {
          productInfo.bannerInfo.push({
            "url": bannerArr[i]
          });
        }

        var weixinArr = res.data.data.weixin_images.split('|');
        for (var i = 0, h = weixinArr.length; i < h; i++) {
          productInfo.weixinInfo.push({
            "url": weixinArr[i]
          });
        }

        var index=0
        if (res.data.data.discharge_type == '国三'){
          index = 0
        } else if (res.data.data.discharge_type == '国四'){
          index = 1
        } else if (res.data.data.discharge_type == '国五') {
          index = 2
        }

        that.setData({
          info: res.data.data,
          region: res.data.data.area.split(','),
          productInfo: productInfo,
          bannerInfoUrl: bannerArr,
          weixinInfoUrl: weixinArr,
          picker1Value: index,
          picker1Range: ['国三', '国四', '国五'],
          dateValue: res.data.data.ilicense_time.substring(0, 7),
          dateValues: res.data.data.ifactory_time.substring(0, 7),
          is_license: (res.data.data.iis_license==1)? true:false,
          checolors: that.data.checolor.indexOf(res.data.data.color),
          baoxiansj: that.data.baoxian.indexOf(res.data.data.insurance_time)
        });

        wx.hideLoading();

        console.log('radio=>' + that.data.is_license)
      },
      fail: function () {
        // fail
        wx.showToast({
          title: '网络请求异常',
          duration: 2000
        });
      }
    });
  },



  bindChooiceProduct: function (e) {



    console.log('11111111--------'+e);
    var that = this;
    var type = e.target.dataset.type;
    var num = 9
    console.log(that.data.productInfo.bannerInfo);

    if (type == 1) {
      var have_num = that.data.productInfo.bannerInfo.length;
      if (have_num > 8) {
        wx.showToast({
          title: '最多上传9张',
          icon: 'success',
          mask: true
        })
        return;
      }
    } else {
      num = 1;
      var have_num = that.data.productInfo.weixinInfo.length ;
      if (have_num > 0) {
        wx.showToast({
          title: '最多上传1张',
          icon: 'success',
          mask: true
        })
        return;
      }
    }

    wx.chooseImage({
      count: num - have_num,  //最多可以选择的图片总数  
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有  
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有  
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片  
        var tempFilePaths = res.tempFilePaths;
        //启动上传等待中...  
        wx.showToast({
          title: '正在上传...',
          icon: 'loading',
          mask: true,
          duration: 10000
        })
        var uploadImgCount = 0;
        for (var i = 0, h = tempFilePaths.length; i < h; i++) {
          wx.uploadFile({
            url: getApp().d.hostUrl + 'api/upload/image',
            filePath: tempFilePaths[i],
            name: 'image',
            formData: {
              'imgIndex': i
            },
            header: {
              "Content-Type": "multipart/form-data",
              'mchnt': getApp().d.mchnt 
            },

            success: function (res) {
              console.log('上传图片 => ' + res);
              if (type == 1) {
                var have_num = that.data.productInfo.bannerInfo.length;
                if (have_num > 8) {
                  wx.showToast({
                    title: '最多上传9张',
                    icon: 'success',
                    mask: true
                  })
                  return;
                }
              } else {
                num = 1;
                var have_num = that.data.productInfo.weixinInfo.length;
                if (have_num > 0) {
                  wx.showToast({
                    title: '最多上传1张',
                    icon: 'success',
                    mask: true
                  })
                  return;
                }
              }
              uploadImgCount++;
              var data = JSON.parse(res.data);
              //服务器返回格式: { "Catalog": "testFolder", "FileName": "1.jpg", "Url": "https://test.com/1.jpg" }

              var productInfo = that.data.productInfo;
              var bannerInfoUrl = that.data.bannerInfoUrl;
              var weixinInfoUrl = that.data.weixinInfoUrl;

              if (type == 1) {
                if (productInfo.bannerInfo == null) {
                  productInfo.bannerInfo = [];
                }
                productInfo.bannerInfo.push({
                  "url": data.data
                });
                if (bannerInfoUrl == null) {
                  bannerInfoUrl = [];
                }
                bannerInfoUrl.push(data.data);
              } else {
                if (productInfo.weixinInfo == null) {
                  productInfo.weixinInfo = [];
                }
                productInfo.weixinInfo.push({
                  "url": data.data
                });
                if (weixinInfoUrl == null) {
                  weixinInfoUrl = [];
                }
                weixinInfoUrl.push(data.data);
              }

              that.setData({
                productInfo: productInfo,
                weixinInfoUrl: weixinInfoUrl,
                bannerInfoUrl: bannerInfoUrl
              });

              console.log(that.data);
              //如果是最后一张,则隐藏等待中  
              if (uploadImgCount == tempFilePaths.length) {
                wx.hideToast();
              }
            },
            fail: function (res) {
              wx.hideToast();
              wx.showModal({
                title: '错误提示',
                content: '上传图片失败',
                showCancel: false,
                success: function (res) { }
              })
            }
          });
        }
      }
    });
  },


  //表单提交按钮
  formSubmit: function (e) {
    var that = this;
    
    //检测登录
    if (!wx.getStorageSync('sk')) {
      app.login();
    }
  
    console.log('form发生了submit事件，携带数据为：', e)
    var formData = e.detail.value; 
    formData.images = that.data.bannerInfoUrl;
    formData.weixin_images = that.data.weixinInfoUrl;
    formData.is_license = that.data.is_license ? 1 : 0;
    formData.discharge_type = that.data.picker1Range[that.data.picker1Value];
    formData.insurance_time = that.data.baoxian[that.data.baoxiansj];
    // formData.color = that.data.checolor[that.data.checolors];
    console.log('formData:' + formData);


    if (!formData.money || formData.money == '' || formData.money <= 0) {
      wx.showModal({
        title: '提示',
        showCancel: false,
        content: '批发价格不正确',
      })
      return;
    }

    if (!formData.type || formData.type == '') {
      wx.showModal({
        title: '提示',
        showCancel: false,
        content: '车型不能为空',
      })
      return;
    }

    if (!formData.actual_mileage || formData.actual_mileage == '' || formData.money < 0) {
      wx.showModal({
        title: '提示',
        showCancel: false,
        content: '实际里程不正确',
      })
      return;
    }

    if (!formData.describe || formData.describe == '') {
      wx.showModal({
        title: '提示',
        showCancel: false,
        content: '车况描述不能为空',
      })
      return;
    }

    if (!formData.phone || formData.phone == '' || formData.phone.length != 11) {
      wx.showModal({
        title: '提示',
        content: '联系电话不正确',
        showCancel: false
      })
      return;
    }

    if (!formData.color || formData.color == '') {
      wx.showModal({
        title: '提示',
        showCancel: false,
        content: '车体颜色不正确',
      })
      return;
    }


    wx.request({
      url: app.d.hostUrl + 'api/car/save',
      data: formData,
      method: 'POST',
      header: {
        'Content-Type': 'application/json',
        'mchnt': getApp().d.mchnt 
      },

      success: function (res) {
        console.log(res)
        if (res.data.code == 1) {
          wx.showModal({
            title: '提示',
            showCancel: false,
            content: res.data.message,
            success: function (r) {
              console.log(r);

              that.setData({
                register: null,
                productInfo: null,
                picker1Value: 0,
                picker1Range: ['国三', '国四', '国五'],
                timeValue: '08:08',
                dateValue: util.formatDateTime(new Date()).substring(0, 7),
                dateValues: util.formatDateTime(new Date()).substring(0, 7),
                region: ['广东省', '广州市', '海珠区'],
                customItem: '全部',
                checolors: 0,
                baoxiansj: 0
              });
              wx.switchTab({
                url: '../cms/index',
              })
            }
          })
        } else {
          wx.showToast({
            title: res.data.message,
            duration: 2000
          });
        }
      },

      fail: function () {
        // fail
        wx.showToast({
          title: '网络请求异常',
          duration: 2000
        });
      }
    });
    
  },


  //删除图片
  delImage: function (e) {
    var that = this;
    var index = e.target.dataset.index;
    var type = e.target.dataset.type;
    var productInfo = that.data.productInfo;
    var weixinInfoUrl = that.data.weixinInfoUrl;
    var bannerInfoUrl = that.data.bannerInfoUrl;
    wx.showModal({
      title: '提示',
      content: '确认要删除此照片吗?',
      success: function (res) {
        if (res.confirm) {

          console.log(productInfo);
          if (type == 1) {
            if (productInfo.bannerInfo != null) {
              productInfo.bannerInfo.splice(index, 1)
              bannerInfoUrl.splice(index, 1);
              that.setData({
                productInfo: productInfo,
                bannerInfoUrl: bannerInfoUrl
              });
            }
          } else {
            if (productInfo.weixinInfo != null) {
              productInfo.weixinInfo.splice(index, 1)
              weixinInfoUrl.splice(index, 1);
              that.setData({
                productInfo: productInfo,
                weixinInfoUrl: weixinInfoUrl
              });
            }
          }

        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },

  radioChange: function (e) {
    console.log('radio发生change事件，携带value值为：', e.detail.value)
    var is_license = (e.detail.value == 1) ? true : false;
    var that = this;
    that.setData({
      is_license: is_license
    })
  }

})
